package com.qu.waibao.home.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;

import com.alibaba.mobileim.YWAPI;
import com.alibaba.mobileim.YWIMKit;
import com.alipay.sdk.app.PayTask;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMapOptions;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.SupportMapFragment;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.map.TextureSupportMapFragment;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.example.xlhratingbar_lib.XLHRatingBar;
import com.google.gson.reflect.TypeToken;
import com.othershe.nicedialog.BaseNiceDialog;
import com.othershe.nicedialog.NiceDialog;
import com.othershe.nicedialog.ViewConvertListener;
import com.othershe.nicedialog.ViewHolder;
import com.qu.waibao.AppConfig;
import com.qu.waibao.R;
import com.qu.waibao.baidu.LocationUtils;
import com.qu.waibao.base.BaseActivity;
import com.qu.waibao.base.BaseRecyclerAdapter;
import com.qu.waibao.bean.Detail;
import com.qu.waibao.bean.PayResult;
import com.qu.waibao.home.adpater.KefuAdapter;
import com.qu.waibao.interf.XnetCallBack;
import com.qu.waibao.network.ActionUtil;
import com.qu.waibao.network.NetManager;
import com.qu.waibao.utils.GsonUtil;
import com.qu.waibao.utils.ImageLoader;
import com.qu.waibao.utils.LogUtil;
import com.qu.waibao.utils.PayUitl;
import com.qu.waibao.utils.TDevice;
import com.qu.waibao.utils.TimeUtil;
import com.qu.waibao.utils.ToastUtil;
import com.qu.waibao.widget.PictureDetailLayout;
import com.qu.waibao.widget.TimerTextView;
import com.qu.waibao.widget.TweetPicturesLayout;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import info.wangchen.simplehud.SimpleHUD;

public class PublishDetailActivity extends BaseActivity implements View.OnClickListener{
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_sure)
    TextView tv_sure;
    @BindView(R.id.tv_gou)
    TextView tv_gou;
    @BindView(R.id.tv_call)
    TextView tv_call;
    @BindView(R.id.iv_publish)
    ImageView iv_publish;

    @BindView(R.id.iv_photo)
    ImageView iv_photo;
    @BindView(R.id.tv_state)
    TextView tv_state;
    @BindView(R.id.tv_dao)
    TimerTextView tv_dao;
    @BindView(R.id.ll_dao)
    LinearLayout ll_dao;

    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_phone)
    TextView tv_phone;
    @BindView(R.id.tv_address)
    TextView tv_address;
    @BindView(R.id.tv_distance)
    TextView tv_distance;
    @BindView(R.id.tv_tishi)
    TextView tv_tishi;

    @BindView(R.id.tv_nick)
    TextView tv_nick;
    @BindView(R.id.tv_type)
    TextView tv_type;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.tv_payment_time)
    TextView tv_payment_time;
    @BindView(R.id.tv_des)
    TextView tv_des;
    @BindView(R.id.ll_images)
    LinearLayout ll_images;
    @BindView(R.id.mTweetPicturesLayout)
    PictureDetailLayout mTweetPicturesLayout;

    @BindView(R.id.ll_qingdan)
    LinearLayout ll_qingdan;
    @BindView(R.id.ll_finish)
    LinearLayout ll_finish;
    @BindView(R.id.tv_number)
    TextView tv_number;
    @BindView(R.id.tv_svreice_type)
    TextView tv_svreice_type;
    @BindView(R.id.tv_publish_time)
    TextView tv_publish_time;
    @BindView(R.id.tv_qiang_name)
    TextView tv_qiang_name;
    @BindView(R.id.tv_qiang_time)
    TextView tv_qiang_time;
    @BindView(R.id.tv_qiang_phone)
    TextView tv_qiang_phone;
    @BindView(R.id.tv_finish_time)
    TextView tv_finish_time;

    @BindView(R.id.tv_cancel)
    TextView tv_cancel;
    @BindView(R.id.tv_zhuijia)
    TextView tv_zhuijia;
    @BindView(R.id.tv_finish)
    TextView tv_finish;
    @BindView(R.id.tv_accept)
    TextView tv_accept;
    @BindView(R.id.tv_comment)
    TextView tv_comment;
    @BindView(R.id.tv_payment)
    TextView tv_payment;
    @BindView(R.id.rl_operator)
    RelativeLayout rl_operator;
    @BindView(R.id.map)
    TextureMapView mMapView;
    BaiduMap mBaidumap = null;
    private String latitude = "";
    private String longitude = "";
    private String serviceid = "";
    private  Detail detail;
    private String paytype = "";
    private IWXAPI api;//微信支付参数
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("com.qu.waibao.PAYMENTSUCCESS")){
                requestData();
            }
        }
    };
    @Override
    protected boolean initBundle(Bundle bundle) {
        if(bundle != null){
            serviceid = bundle.getString("serviceid");
        }
        return super.initBundle(bundle);
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_publish_detail;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        tv_title.setText("订单详情");
        iv_publish.setVisibility(View.GONE);
        tv_sure.setText("修改发布");
        //初始地图
        mBaidumap = mMapView.getMap();
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);
        mBaidumap.setMapStatus(msu);
        initView();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.qu.waibao.PAYMENTSUCCESS");
        registerReceiver(receiver,intentFilter);
    }
    private void initView() {
        View child = mMapView.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);
        }
        // 不显示地图上比例尺
        mMapView.showScaleControl(false);
        // 不显示地图缩放控件（按钮控制栏）
        mMapView.showZoomControls(false);
        mBaidumap.getUiSettings().setScrollGesturesEnabled(false);
        mBaidumap.getUiSettings().setZoomGesturesEnabled(true);
        mBaidumap.getUiSettings().setRotateGesturesEnabled(false);
        mBaidumap.getUiSettings().setOverlookingGesturesEnabled(false);
        mBaidumap.getUiSettings().setCompassEnabled(false);
    }
    public void initOverlay(double sLag,double slng) {
        LatLng llA = new LatLng(sLag, slng);
        MarkerOptions ooA = new MarkerOptions().position(llA)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.location_middle))
                .zIndex(9);
        mBaidumap.addOverlay(ooA);
        // 设置有效区域
        LatLngBounds bounds = new LatLngBounds.Builder()
                .include(llA).build();
        MapStatusUpdate u = MapStatusUpdateFactory
                .newLatLngBounds(bounds,mMapView.getWidth(),mMapView.getHeight());
        mBaidumap.setMapStatus(u);

    }
    @Override
    protected void initData() {
        super.initData();
        if(LocationUtils.Mylocation != null){
            latitude = String.valueOf(LocationUtils.Mylocation.getLatitude());
            longitude = String.valueOf(LocationUtils.Mylocation.getLongitude());
        }
        requestData();
    }
    @OnClick({R.id.ll_back,R.id.tv_accept,R.id.tv_zhuijia,R.id.tv_copy,R.id.tv_gou,R.id.tv_call,
            R.id.tv_cancel,R.id.tv_finish,R.id.tv_payment,R.id.tv_comment,R.id.tv_sure})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_back:
                finish();
                break;
            case R.id.tv_sure:
                //Intent intent = new Intent(this,PublishActivity.class)
                break;
            case R.id.tv_gou: //沟通
                if(detail != null) {
                    YWIMKit mIMKit = YWAPI.getIMKitInstance(AppConfig.getString("userid"), AppConfig.APP_KEY);
                    Intent kefu = mIMKit.getChattingActivityIntent(detail.getDetail().getUserid(), AppConfig.APP_KEY);//别人的uesrId
                    startActivity(kefu);
                }
                break;
            case R.id.tv_cancel:
                NiceDialog.init()
                        .setLayoutId(R.layout.confirm_dialog_layout)     //设置dialog布局文件
                        .setConvertListener(new ViewConvertListener() {     //进行相关View操作的回调
                            @Override
                            public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                                holder.setOnClickListener(R.id.tv_cancel, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                    }
                                });
                                holder.setOnClickListener(R.id.tv_sure, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                        cancelOrFinish(serviceid,"1");
                                    }
                                });
                            }
                        })
                        .setMargin(50)
                        .setDimAmount(0.3f)     //调节灰色背景透明度[0-1]，默认0.5f
                        .setShowBottom(false)     //是否在底部显示dialog，默认flase
                        .setOutCancel(true)     //点击dialog外是否可取消，默认true
                        .show(getSupportFragmentManager());     //显示dialog
                break;
            case R.id.tv_finish:
                cancelOrFinish(serviceid,"2");
                break;
            case R.id.tv_payment:
                if(detail != null){
                    paymentDialog(detail.getDetail().getOrdercode(),detail.getMoney_getorder()+"");
                }
                break;
            case R.id.tv_comment:
                NiceDialog.init()
                        .setLayoutId(R.layout.comment_dialog_layout)     //设置dialog布局文件
                        .setConvertListener(new ViewConvertListener() {     //进行相关View操作的回调
                            @Override
                            public void convertView(final ViewHolder holder, final BaseNiceDialog dialog) {
                                holder.setOnClickListener(R.id.tv_submit, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        XLHRatingBar bar = holder.getView(R.id.ratingBar);
                                        EditText remark = holder.getView(R.id.et_remark);
                                        String score = bar.getCountSelected()+"";
                                        String comment = remark.getText().toString();
                                        LogUtil.Loge("TAG",comment+"::"+score);
                                        if(TextUtils.isEmpty(comment)){
                                            ToastUtil.show(PublishDetailActivity.this,"评论不能为空");
                                            return;
                                        }
                                        comment(serviceid,comment,score);
                                        dialog.dismiss();
                                    }
                                });

                                holder.setOnClickListener(R.id.iv_delete, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                    }
                                });

                            }
                        })
                        .setMargin(30)
                        .setDimAmount(0.3f)     //调节灰色背景透明度[0-1]，默认0.5f
                        .setShowBottom(false)     //是否在底部显示dialog，默认flase
                        .setOutCancel(true)     //点击dialog外是否可取消，默认true
                        .show(getSupportFragmentManager());     //显示dialog
                break;
            case R.id.tv_call:
                TDevice.openDial(this, tv_phone.getText().toString());
                break;
            case R.id.tv_copy:
                String number = tv_number.getText().toString();
                TDevice.copyTextToBoard(number);
                break;
            case R.id.tv_accept:
                accept(serviceid);
                break;
            case R.id.tv_zhuijia:
                NiceDialog.init()
                        .setLayoutId(R.layout.zhuijia_dialog_layout)     //设置dialog布局文件
                        .setConvertListener(new ViewConvertListener() {     //进行相关View操作的回调
                            @Override
                            public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                                final EditText et_money = holder.getView(R.id.et_money);
                                holder.setOnClickListener(R.id.tv_cancel, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        dialog.dismiss();
                                    }
                                });

                                holder.setOnClickListener(R.id.tv_sure, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        final String moeny = et_money.getText().toString().trim();
                                        if(TextUtils.isEmpty(moeny)){
                                            ToastUtil.show(PublishDetailActivity.this,"追加的金额不能为空");
                                            return;
                                        }
                                        dialog.dismiss();
                                        zhujia(serviceid,moeny);
                                    }
                                });
                            }
                        })
                        .setMargin(16)
                        .setDimAmount(0.3f)     //调节灰色背景透明度[0-1]，默认0.5f
                        .setShowBottom(false)     //是否在底部显示dialog，默认flase
                        .setOutCancel(true)     //点击dialog外是否可取消，默认true
                        .show(getSupportFragmentManager());     //显示dialog
                break;
        }
    }

    public void requestData(){
        Map<String,String> map = new HashMap<>();
        map.put("action", ActionUtil.service_detail_get);
        map.put("userid",AppConfig.getString("userid"));
        map.put("serviceid",serviceid);
        map.put("latitude",latitude);
        map.put("longitude",longitude);
        NetManager.getInstance().request(this, map, true, new XnetCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
                detail = GsonUtil.createGson().fromJson(result,
                        new TypeToken<Detail>(){}.getType());
                //构建地图
                if(!TextUtils.isEmpty(detail.getDetail().getLatitude())) {
                    initOverlay(Double.valueOf(detail.getDetail().getLatitude()),
                            (Double.valueOf(detail.getDetail().getLongitude())));
                }

                String state = detail.getDetail().getState();
                tv_nick.setText(detail.getDetail().getSecondname());
                tv_money.setText("¥"+detail.getDetail().getMoney_total());
                tv_type.setText(detail.getDetail().getServicecategoryname());
                tv_payment_time.setText(detail.getDetail().getCreatedate());
                tv_des.setText(detail.getDetail().getRemark());

                if(TextUtils.isEmpty(detail.getDetail().getImgs())){
                    ll_images.setVisibility(View.GONE);
                }else {
                    String[] images = detail.getDetail().getImgs().split(",");
                    mTweetPicturesLayout.setImage(images,PublishDetailActivity.this);
                }

                tv_state.setText(detail.getDetail().getState());
                tv_number.setText(detail.getDetail().getOrdercode());
                tv_svreice_type.setText(detail.getDetail().getServicecategoryname());
                tv_publish_time.setText(detail.getDetail().getCreatedate());
                tv_qiang_name.setText(detail.getDetail().getName_get());
                tv_qiang_time.setText(detail.getDetail().getCreatedate_get());
                tv_qiang_phone.setText(detail.getDetail().getPhone_get());
                tv_finish_time.setText(detail.getDetail().getFinishdate());
                if(state.equals("待抢单")){
                    ll_dao.setVisibility(View.VISIBLE);
                    long unitx = TimeUtil.getUnitx(detail.getDetail().getIndate());
                    Log.e("TAG","unitx---"+unitx);
                    if(unitx > 0){
                        tv_dao.setTimes(unitx);
                        tv_dao.start();
                    }
                    ll_qingdan.setVisibility(View.GONE);
                    ll_finish.setVisibility(View.GONE);
                }else if(state.equals("待完成")){
                    ll_dao.setVisibility(View.GONE);
                    ll_qingdan.setVisibility(View.VISIBLE);
                }else if(state.equals("已完成")){
                    ll_dao.setVisibility(View.GONE);
                    ll_qingdan.setVisibility(View.VISIBLE);
                    ll_finish.setVisibility(View.VISIBLE);
                }else if(state.equals("待支付")){
                    ll_dao.setVisibility(View.GONE);
                    ll_qingdan.setVisibility(View.GONE);
                    ll_finish.setVisibility(View.GONE);
                }else if(state.equals("已取消")){
                    ll_dao.setVisibility(View.GONE);
                    ll_qingdan.setVisibility(View.GONE);
                    ll_finish.setVisibility(View.GONE);
                }


                // 订单的显示
                int card = AppConfig.getInt("card");
                String userid = AppConfig.getString("userid");
                String detail_userid = detail.getDetail().getUserid();
                String user_get = detail.getDetail().getUserid_get();
                if(userid.equals(detail_userid)){
                    //tv_sure.setVisibility(View.VISIBLE);//发布者
                    tv_tishi.setVisibility(View.GONE);
                    tv_gou.setEnabled(false);
                    tv_call.setEnabled(false);
                    tv_gou.setTextColor(Color.parseColor("#cccccc"));
                    tv_call.setTextColor(Color.parseColor("#cccccc"));
                    tv_gou.setCompoundDrawablesWithIntrinsicBounds(R.drawable.xq_toutong1,0,0,0);
                    tv_call.setCompoundDrawablesWithIntrinsicBounds(R.drawable.qx_dianhua1,0,0,0);
                    //显示发布信息
                    tv_name.setText("联系人："+detail.getDetail().getLinkman());
                    tv_phone.setText(detail.getDetail().getLinkphone());
                    tv_address.setText("地址："+detail.getDetail().getAddress());
                    tv_distance.setText(detail.getDetail().getDistance()+"km");
                    if(state.equals("待支付")){
                        rl_operator.setVisibility(View.VISIBLE);
                        tv_cancel.setVisibility(View.VISIBLE);
                        tv_payment.setVisibility(View.VISIBLE);
                        tv_zhuijia.setVisibility(View.GONE);
                        tv_comment.setVisibility(View.GONE);
                        tv_accept.setVisibility(View.GONE);
                        tv_finish.setVisibility(View.GONE);
                    }else if(state.equals("待抢单")){
                        rl_operator.setVisibility(View.VISIBLE);
                        tv_cancel.setVisibility(View.VISIBLE);
                        tv_payment.setVisibility(View.GONE);
                        tv_zhuijia.setVisibility(View.GONE);
                        tv_comment.setVisibility(View.GONE);
                        tv_accept.setVisibility(View.GONE);
                        tv_finish.setVisibility(View.GONE);
                    }else if(state.equals("待完成")){
                        rl_operator.setVisibility(View.VISIBLE);
                        tv_cancel.setVisibility(View.GONE);
                        tv_payment.setVisibility(View.GONE);
                        tv_zhuijia.setVisibility(View.VISIBLE);
                        tv_comment.setVisibility(View.GONE);
                        tv_accept.setVisibility(View.GONE);
                        tv_finish.setVisibility(View.VISIBLE);
                    } else if(state.equals("已完成")){
                        rl_operator.setVisibility(View.VISIBLE);
                        tv_cancel.setVisibility(View.GONE);
                        tv_payment.setVisibility(View.GONE);
                        tv_zhuijia.setVisibility(View.GONE);
                        tv_accept.setVisibility(View.GONE);
                        tv_finish.setVisibility(View.GONE);
                        if(detail.getDetail().getIfcommented_user().equals("0")){
                            tv_comment.setVisibility(View.VISIBLE);
                        }else {
                            tv_comment.setVisibility(View.GONE);
                        }
                    }else if(state.equals("已取消")){
                        rl_operator.setVisibility(View.GONE);
                    }
                }else{

                    if(userid.equals(user_get)){  //接单者
                        tv_tishi.setVisibility(View.GONE);
                        tv_gou.setEnabled(true);
                        tv_call.setEnabled(true);
                        tv_gou.setTextColor(Color.parseColor("#333333"));
                        tv_call.setTextColor(Color.parseColor("#333333"));
                        tv_gou.setCompoundDrawablesWithIntrinsicBounds(R.drawable.xq_toutong2,0,0,0);
                        tv_call.setCompoundDrawablesWithIntrinsicBounds(R.drawable.xq_dianhua2,0,0,0);
                        //显示发布信息
                        tv_name.setText("联系人："+detail.getDetail().getLinkman());
                        tv_phone.setText(detail.getDetail().getLinkphone());
                        tv_address.setText("地址："+detail.getDetail().getAddress());
                        tv_distance.setText(detail.getDetail().getDistance()+"km");

                        if(state.equals("待完成")){
                            tv_gou.setEnabled(true);
                            tv_call.setEnabled(true);
                            tv_gou.setTextColor(Color.parseColor("#333333"));
                            tv_call.setTextColor(Color.parseColor("#333333"));
                            tv_gou.setCompoundDrawablesWithIntrinsicBounds(R.drawable.xq_toutong2,0,0,0);
                            tv_call.setCompoundDrawablesWithIntrinsicBounds(R.drawable.xq_dianhua2,0,0,0);
                            rl_operator.setVisibility(View.GONE);
                        } else if(state.equals("已完成")){
                            rl_operator.setVisibility(View.VISIBLE);
                            tv_gou.setEnabled(true);
                            tv_call.setEnabled(true);
                            tv_gou.setTextColor(Color.parseColor("#333333"));
                            tv_call.setTextColor(Color.parseColor("#333333"));
                            tv_gou.setCompoundDrawablesWithIntrinsicBounds(R.drawable.xq_toutong2,0,0,0);
                            tv_call.setCompoundDrawablesWithIntrinsicBounds(R.drawable.xq_dianhua2,0,0,0);
                            tv_cancel.setVisibility(View.GONE);
                            tv_payment.setVisibility(View.GONE);
                            tv_zhuijia.setVisibility(View.GONE);
                            tv_accept.setVisibility(View.GONE);
                            tv_finish.setVisibility(View.GONE);
                            if(detail.getDetail().getIfcommented_server().equals("0")){
                                tv_comment.setVisibility(View.VISIBLE);
                            }else {
                                tv_comment.setVisibility(View.GONE);
                            }
                        }
                    }else {

                        if(!userid.equals(detail_userid) && card == 1){ //车主
                            //显示发布信息
                            if(!TextUtils.isEmpty(detail.getDetail().getLinkman())) {
                                tv_name.setText("联系人：" + detail.getDetail().getLinkman().substring(0, 1) + "*");
                            }
                            if(!TextUtils.isEmpty(detail.getDetail().getLinkphone())){
                                tv_phone.setText(detail.getDetail().getLinkphone().substring(0,3)+"****"
                                        +detail.getDetail().getLinkphone().substring(8,11));
                            }
                            if(!TextUtils.isEmpty(detail.getDetail().getAddress())){
                                tv_address.setText("地址："+detail.getDetail().getAddress().substring(0,2)+"********");
                            }
                            tv_gou.setEnabled(false);
                            tv_call.setEnabled(false);
                            tv_gou.setTextColor(Color.parseColor("#cccccc"));
                            tv_call.setTextColor(Color.parseColor("#cccccc"));
                            tv_gou.setCompoundDrawablesWithIntrinsicBounds(R.drawable.xq_toutong1,0,0,0);
                            tv_call.setCompoundDrawablesWithIntrinsicBounds(R.drawable.qx_dianhua1,0,0,0);
                            rl_operator.setVisibility(View.GONE);
                            tv_tishi.setVisibility(View.VISIBLE);
                        }else if(!userid.equals(detail_userid)){ //商家或者修理工
                            if(card == 2|| card == 3){
                                if(state.equals("待抢单")){
                                    //显示发布信息
                                    if(!TextUtils.isEmpty(detail.getDetail().getLinkman())) {
                                        tv_name.setText("联系人：" + detail.getDetail().getLinkman().substring(0, 1) + "*");
                                    }
                                    if(!TextUtils.isEmpty(detail.getDetail().getLinkphone())){
                                        tv_phone.setText(detail.getDetail().getLinkphone().substring(0,3)+"****"
                                                +detail.getDetail().getLinkphone().substring(8,11));
                                    }
                                    if(!TextUtils.isEmpty(detail.getDetail().getAddress())){
                                        tv_address.setText("地址："+detail.getDetail().getAddress().substring(0,2)+"********");
                                    }
                                    tv_distance.setText("**km");
                                    rl_operator.setVisibility(View.VISIBLE);
                                    tv_tishi.setVisibility(View.VISIBLE);

                                    tv_gou.setEnabled(false);
                                    tv_call.setEnabled(false);
                                    tv_gou.setTextColor(Color.parseColor("#cccccc"));
                                    tv_call.setTextColor(Color.parseColor("#cccccc"));
                                    tv_gou.setCompoundDrawablesWithIntrinsicBounds(R.drawable.xq_toutong1,0,0,0);
                                    tv_call.setCompoundDrawablesWithIntrinsicBounds(R.drawable.qx_dianhua1,0,0,0);
                                    tv_payment.setVisibility(View.GONE);
                                    tv_zhuijia.setVisibility(View.GONE);
                                    tv_comment.setVisibility(View.GONE);
                                    tv_accept.setVisibility(View.VISIBLE);
                                    tv_finish.setVisibility(View.GONE);
                                    tv_cancel.setVisibility(View.GONE);
                                }else if(state.equals("待支付")){
                                    tv_tishi.setVisibility(View.GONE);
                                    //显示发布信息
                                    tv_name.setText("联系人："+detail.getDetail().getLinkman());
                                    tv_phone.setText(detail.getDetail().getLinkphone());
                                    tv_address.setText("地址："+detail.getDetail().getAddress());
                                    tv_distance.setText(detail.getDetail().getDistance()+"km");
                                    rl_operator.setVisibility(View.GONE);
                                } else if(state.equals("待完成")){
                                    tv_tishi.setVisibility(View.GONE);
                                    //显示发布信息
                                    tv_name.setText("联系人："+detail.getDetail().getLinkman());
                                    tv_phone.setText(detail.getDetail().getLinkphone());
                                    tv_address.setText("地址："+detail.getDetail().getAddress());
                                    tv_distance.setText(detail.getDetail().getDistance()+"km");
                                    rl_operator.setVisibility(View.GONE);
                                } else if(state.equals("已完成")){
                                    tv_tishi.setVisibility(View.GONE);
                                    //显示发布信息
                                    tv_name.setText("联系人："+detail.getDetail().getLinkman());
                                    tv_phone.setText(detail.getDetail().getLinkphone());
                                    tv_address.setText("地址："+detail.getDetail().getAddress());
                                    tv_distance.setText(detail.getDetail().getDistance()+"km");
                                    rl_operator.setVisibility(View.GONE);
                                }else if(state.equals("已取消")){
                                    tv_tishi.setVisibility(View.GONE);
                                    //显示发布信息
                                    tv_name.setText("联系人："+detail.getDetail().getLinkman());
                                    tv_phone.setText(detail.getDetail().getLinkphone());
                                    tv_address.setText("地址："+detail.getDetail().getAddress());
                                    tv_distance.setText(detail.getDetail().getDistance()+"km");
                                    rl_operator.setVisibility(View.GONE);
                                }
                            }
                        }

                    }

                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        tv_dao.stop();
        super.onDestroy();
        if(receiver != null){
            unregisterReceiver(receiver);
            receiver = null;
        }

    }

    public void cancelOrFinish(String serviceid, String opt){
        Map<String,String> map = new HashMap<>();
        map.put("action",ActionUtil.service_opt_set);
        map.put("userid",AppConfig.getString("userid"));
        map.put("serviceid",serviceid);
        map.put("opt",opt);
        NetManager.getInstance().request(this, map, true, new XnetCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
                ToastUtil.show(PublishDetailActivity.this,msg);
                requestData();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    //接受订单
    public void accept(String serviceid){
        Map<String,String> map = new HashMap<>();
        map.put("action",ActionUtil.service_opt_getorder_set);
        map.put("userid",AppConfig.getString("userid"));
        map.put("serviceid",serviceid);
        RequestParams params = NetManager.getUrl(map);
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject object = new JSONObject(result);
                    if(object.optInt("status") == 1){
                        ToastUtil.show(PublishDetailActivity.this,object.optString("message"));
                        JSONObject jsonObject = object.optJSONObject("result");
                        if(jsonObject.optString("state_pay").equals("未支付")){
                            paymentDialog(object.optString("ordercode"),detail.getDetail().getMoney_total());
                        }else {
                            requestData();
                        }
                    }else {
                        ToastUtil.show(PublishDetailActivity.this,object.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }
    public void zhujia(String serviceid, final String money){
        Map<String,String> map = new HashMap<>();
        map.put("action",ActionUtil.service_addmoney_set);
        map.put("userid",AppConfig.getString("userid"));
        map.put("serviceid",serviceid);
        map.put("moneypay_online",money);
        RequestParams params = NetManager.getUrl(map);
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject object = new JSONObject(result);
                    if(object.optInt("status") == 1){
                        ToastUtil.show(PublishDetailActivity.this,object.optString("message"));
                        paymentDialog(object.optString("ordercode"),money);
                    }else {
                        ToastUtil.show(PublishDetailActivity.this,object.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void comment(String serviceid,String remark,String score){
        Map<String,String> map = new HashMap<>();
        map.put("action",ActionUtil.order_comments_set);
        map.put("userid",AppConfig.getString("userid"));
        map.put("serviceid",serviceid);
        map.put("remark",remark);
        map.put("score",score);
        NetManager.getInstance().request(this, map, true, new XnetCallBack() {
            @Override
            public void onSuccess(String result, String msg) {
                ToastUtil.show(PublishDetailActivity.this,msg);
                requestData();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void paymentDialog(final String ordercode, final String price){
        NiceDialog.init()
                .setLayoutId(R.layout.zhifu_dialog_layout)     //设置dialog布局文件
                .setConvertListener(new ViewConvertListener() {     //进行相关View操作的回调
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        TextView textView = holder.getView(R.id.tv_tv_title);
                        textView.setText("支付金额"+price);
                        final TextView tv_weixin = holder.getView(R.id.tv_weixin);
                        final TextView tv_zhifubao = holder.getView(R.id.tv_tv_zhifubao);
                        holder.setOnClickListener(R.id.ll_weixin, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                tv_weixin.setTextColor(Color.parseColor("#67b8f2"));
                                tv_zhifubao.setTextColor(Color.parseColor("#333333"));
                                paytype = "微信支付";
                            }
                        });

                        holder.setOnClickListener(R.id.ll_zhifubao, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                tv_weixin.setTextColor(Color.parseColor("#333333"));
                                tv_zhifubao.setTextColor(Color.parseColor("#67b8f2"));
                                paytype = "支付宝支付";
                            }
                        });
                        holder.setOnClickListener(R.id.tv_tv_sure, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                getOrderCode(ordercode,paytype);
                            }
                        });
                        holder.setOnClickListener(R.id.iv_delete, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });

                    }
                })
                .setDimAmount(0.3f)     //调节灰色背景透明度[0-1]，默认0.5f
                .setShowBottom(true)     //是否在底部显示dialog，默认flase
                .setOutCancel(true)     //点击dialog外是否可取消，默认true
                .show(getSupportFragmentManager());     //显示dialog
    }
    public void getOrderCode(String ordercode, final String paytype){
        SimpleHUD.showLoadingMessage(this,"",AppConfig.isCanCancel);
        Map<String,String> map = new HashMap<>();
        map.put("action",ActionUtil.order_pay_set);
        map.put("ordercode",ordercode);
        map.put("paytype",paytype);
        RequestParams params = NetManager.getUrl(map);
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if(jsonObject.optInt("status") == 1) {
                        if (paytype.equals("微信支付")) {
                            String optString = jsonObject.optString("prepayinfo");
                            JSONObject payObj = new JSONObject(optString);
                            doWeiXinPay(payObj.optString("appid"), payObj.optString("partnerid"), payObj.optString("prepayid"), payObj.optString("noncestr"),
                                    payObj.optString("timestamp"), payObj.optString("package"), payObj.optString("sign"));
                        } else {
                            JSONObject payObj = jsonObject.optJSONObject("prepayinfo");
                            doAlipay("车捷派服务", "车捷派服务", payObj.optString("OrderCode"),
                                    payObj.optString("url_notify"), payObj.optString("partner"),
                                    payObj.optString("seller"), payObj.optString("private_key"));
                        }
                    }else {
                        ToastUtil.show(PublishDetailActivity.this,jsonObject.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                SimpleHUD.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                SimpleHUD.dismiss();
            }

            @Override
            public void onFinished() {
                SimpleHUD.dismiss();
            }
        });
    }
    public void doWeiXinPay(String appId, String partnerId, String prepayId, String nonceStr,
                            String timeStamp,String packageValue, String sign) {
        SimpleHUD.dismiss();
        api = WXAPIFactory.createWXAPI(this,null);
        api.registerApp(appId);
        PayReq req = new PayReq();
        req.appId			= appId;
        req.partnerId		= partnerId;
        req.prepayId		= prepayId;
        req.nonceStr		= nonceStr;
        req.timeStamp		= timeStamp;
        req.packageValue	= packageValue;
        req.sign			= sign;
        api.sendReq(req);
    }
    public void doAlipay(String subject,String body,String out_trade_no,String notify_url,String partner
            ,String seller,String private_key) {
        // 订单
        String orderInfo = PayUitl.getOrderInfo(subject,body,out_trade_no, notify_url, "0.01",partner,seller);
        // 对订单做RSA 签名
        String sign = PayUitl.sign(orderInfo,private_key);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + PayUitl.getSignType();

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                SimpleHUD.dismiss();
                PayTask alipay = new PayTask(PublishDetailActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo,true);
                PayResult payResult = new PayResult(result);
                final String resultStatus = payResult.getResultStatus();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                        if (TextUtils.equals(resultStatus, "9000")) {
                            ToastUtil.show(PublishDetailActivity.this, "支付成功");
                            Intent intent = new Intent("com.qu.waibao.PAYMENTSUCCESS");
                            sendBroadcast(intent);
                        }else if (TextUtils.equals(resultStatus, "8000")) {
                            // 判断resultStatus 为非“9000”则代表可能支付失败
                            // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                            ToastUtil.show(PublishDetailActivity.this, "支付结果确认中");
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            ToastUtil.show(PublishDetailActivity.this, "支付失败");
                        }
                    }
                });
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

}
